﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace LocalizeString
{
    class Program
    {
        static string LocalizationKey;
        static string LocalizationValue;

        static int Line;
        static int Column;

        static bool IsCode;

        static void Main(string[] args)
        {
            //$(ItemPath)
            //$(CurText)
            //$(CurLine) 
            //$(CurCol)

            IsCode = Path.GetExtension(args[0]).Equals(".cs");

            Line = int.Parse(args[2]) - 1;
            Column = int.Parse(args[3]) - 1;

            if (args.Count() > 0)
            {
                LocalizationValue = args[1];
                CreateLocalizationKey();

                string resourceFilePath = GetResourcePath(args[0]);
                string itemContent = ReadItemContent(args[0]);

                itemContent = ReplaceItemContent(itemContent);
                WriteItemContent(args[0], itemContent);

                XDocument resourceXml = ReadResourceFile(resourceFilePath);
                WriteDataNode(resourceXml);
                resourceXml.Save(resourceFilePath);
            }
        }

        private static string GetResourcePath(string itemPath)
        {
            return itemPath.Replace(Path.GetFileName(itemPath), "")
                + "App_LocalResources/" + Path.GetFileName(itemPath) + ".resx";
        }

        private static void WriteDataNode(XDocument resourceXml)
        {
            XElement root = resourceXml.Element("root");
            root.Add(new XElement("data",
                new XAttribute("name", LocalizationKey),
                new XElement("value", LocalizationValue)));
        }

        private static XDocument ReadResourceFile(string resourceFilePath)
        {
            XDocument resourceXml = null;

            using (StreamReader streamReader = new StreamReader(resourceFilePath))
            {
                resourceXml = XDocument.Parse(streamReader.ReadToEnd());
                streamReader.Close();
            }

            return resourceXml;
        }

        private static void WriteItemContent(string itemPath, string itemContent)
        {
            using (StreamWriter streamWriter = new StreamWriter(itemPath))
            {
                streamWriter.Write(itemContent);
                streamWriter.Close();
            }
        }

        private static string ReplaceItemContent(string itemContent)
        {
            string[] lines = Regex.Split(itemContent, "\r\n");

            string targetLine = lines[Line];

            try
            {
                if (targetLine.Substring(Column - LocalizationValue.Length, LocalizationValue.Length).Equals(LocalizationValue))
                    Column = Column - LocalizationValue.Length;

            }
            catch { }

            string replacePattern;

            if (IsCode)
                replacePattern = "GetLocalResourceObject(\"{0}\").ToString();";
            else
            {
                replacePattern = "<%$ Resources:{0} %>";
                if (!targetLine.Substring(Column - 2, 1).Equals("="))
                {
                    replacePattern = "<asp:Literal runat=\"server\" Text=\"<%$ Resources:{0} %>\" />";
                }
            }

            targetLine = targetLine.Remove(Column, LocalizationValue.Length);
            targetLine = targetLine.Insert(Column, string
                .Format(replacePattern, LocalizationKey));


            lines[Line] = targetLine;

            StringBuilder stringBuilder = new StringBuilder();
            foreach (string line in lines)
            {
                stringBuilder.AppendLine(line);
            }

            return stringBuilder.ToString();
        }

        private static string ReadItemContent(string itemPath)
        {
            string itemContent;

            using (StreamReader streamReader = new StreamReader(itemPath))
            {
                itemContent = streamReader.ReadToEnd();
                streamReader.Close();
            }

            return itemContent;
        }

        private static void CreateLocalizationKey()
        {
            LocalizationKey = string.Empty;
            Regex regex = new Regex("[A-Za-z]+");
            
            foreach (Match match in regex.Matches(LocalizationValue))
            {
                if (!string.IsNullOrEmpty(match.Value))
                {
                    string pascalcase = match.Value;
                    char fchar = pascalcase[0];
                    fchar = char.ToUpper(fchar);

                    pascalcase = pascalcase.Remove(0, 1);
                    pascalcase = pascalcase.Insert(0, fchar.ToString());

                    LocalizationKey += pascalcase;

                    if (LocalizationKey.Length >= 30)
                        break;
                }
            }
        }
    }
}
